import pymysql
from config import DB_CONFIG
import logging

class DBHandler:
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.connect()

    def connect(self):
        try:
            self.conn = pymysql.connect(**DB_CONFIG)
            self.cursor = self.conn.cursor()
            logging.info("数据库连接成功")
        except Exception as e:
            logging.error(f"数据库连接失败: {str(e)}")
            raise

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

    def save_user(self, username, nickname, avatar, location):
        try:
            sql = """
                INSERT INTO users (username, password, nickname, avatar, location)
                VALUES (%s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE
                nickname = VALUES(nickname),
                avatar = VALUES(avatar),
                location = VALUES(location)
            """
            self.cursor.execute(sql, (username, 'default_password', nickname, avatar, location))
            self.conn.commit()
            return self.cursor.lastrowid
        except Exception as e:
            logging.error(f"保存用户信息失败: {str(e)}")
            self.conn.rollback()
            raise

    def save_post(self, user_id, content, media_urls, location):
        try:
            content_type = 1  # 默认为文字类型
            if media_urls:
                content_type = 2 if '.jpg' in media_urls or '.png' in media_urls else 3

            sql = """
                INSERT INTO posts (user_id, content_type, content, media_url, platform, location)
                VALUES (%s, %s, %s, %s, %s, %s)
            """
            self.cursor.execute(sql, (user_id, content_type, content, media_urls, 'weibo', location))
            self.conn.commit()
            return self.cursor.lastrowid
        except Exception as e:
            logging.error(f"保存帖子失败: {str(e)}")
            self.conn.rollback()
            raise

    def save_topic(self, topic_name, description=''):
        try:
            sql = """
                INSERT INTO topics (topic_name, description)
                VALUES (%s, %s)
                ON DUPLICATE KEY UPDATE
                description = VALUES(description)
            """
            self.cursor.execute(sql, (topic_name, description))
            self.conn.commit()
            return self.cursor.lastrowid
        except Exception as e:
            logging.error(f"保存话题失败: {str(e)}")
            self.conn.rollback()
            raise

    def save_post_topic(self, post_id, topic_id):
        try:
            sql = """
                INSERT IGNORE INTO post_topics (post_id, topic_id)
                VALUES (%s, %s)
            """
            self.cursor.execute(sql, (post_id, topic_id))
            self.conn.commit()
        except Exception as e:
            logging.error(f"保存帖子-话题关联失败: {str(e)}")
            self.conn.rollback()
            raise

    def save_interaction(self, user_id, post_id, interaction_type, comment_content=None):
        try:
            sql = """
                INSERT INTO interactions (user_id, post_id, type, comment_content)
                VALUES (%s, %s, %s, %s)
            """
            self.cursor.execute(sql, (user_id, post_id, interaction_type, comment_content))
            self.conn.commit()
        except Exception as e:
            logging.error(f"保存互动信息失败: {str(e)}")
            self.conn.rollback()
            raise

    def save_user_tag(self, user_id, tag_name, weight=1.0):
        try:
            sql = """
                INSERT INTO user_tags (user_id, tag_name, weight)
                VALUES (%s, %s, %s)
                ON DUPLICATE KEY UPDATE
                weight = weight + VALUES(weight)
            """
            self.cursor.execute(sql, (user_id, tag_name, weight))
            self.conn.commit()
        except Exception as e:
            logging.error(f"保存用户标签失败: {str(e)}")
            self.conn.rollback()
            raise

    def get_topic_id(self, topic_name):
        try:
            sql = "SELECT topic_id FROM topics WHERE topic_name = %s"
            self.cursor.execute(sql, (topic_name,))
            result = self.cursor.fetchone()
            return result[0] if result else None
        except Exception as e:
            logging.error(f"获取话题ID失败: {str(e)}")
            raise 